<script lang="ts">
	import RootStore, { type IMMessage } from "@xkit-yx/im-store";
	// @ts-ignore
	import { NimKitCore } from "@xkit-yx/core-kit/dist/uniapp-nim-core";
	import {
		customRedirectTo,
		customReLaunch,
		customSwitchTab,
	} from "./utils/customNavigate";
	import { getMsgContentTipByType } from "./utils/msg";
	import { STORAGE_KEY } from "./utils/constants";
	import { isWxApp } from "./utils";
	// #ifdef APP-PLUS
	// @ts-ignore
	// 推送插件
	const nimPushPlugin = uni.requireNativePlugin("NIMUniPlugin-PluginModule");
	// 音视频通话插件
	//@ts-ignore
	const nimCallKit = (uni.$UIKitCallKit =
		uni.requireNativePlugin("netease-CallKit"));
	// #endif
	const {
		updateManager
	} = require('./common/config.js');
	import {
		checkUserInfo,
		getKey
	} from "./api/login.js"
	export default {
		globalData: {
			//全局配置参数
			barHeight: 0,
			screenWidth: 0,
			screenHeight: 0,
			viewHeight: 0,
			openPay: true
		},
		onLaunch: function(options) {


			uni.getSystemInfo({
				success: function(e) {
					// e.statusBarHeight 是返回的状态栏的高度
					// 在此处可以动态设置状态栏的高度
					// 注意：这里的单位是rpx，如果你需要px，可以根据设备的宽度进行换算
					let statusBarHeight = e.statusBarHeight + 'px';
					// 更新状态栏的样式
					let statusBarStyle = `/deep/ .status-bar { height: ${statusBarHeight} }`
					// 注意：/deep/ 是为了穿透组件边界，确保样式能应用到子组件
					// 在App.vue中可以直接更新全局样式
					plus.navigator.setStatusBarStyle({
						style: 'dark' // 可以设置状态栏的样式为深色
					});
				}
			});


			let that = this;
			//	#ifdef APP-PLUS
			plus.screen.lockOrientation('portrait-primary'); //竖屏正方向锁定

			updateManager();
			//#endif

			// #ifndef APP-PLUS
			// 是否开启支付
			// that.$http.get('/saleconfig/openPayment').then(res => {
			// 	if (res && res.code == 200) {
			// 		that.globalData.openPay = res.openPayment;
			// 	}
			// });
			//#endif


			if (options.query.code) {
				uni.setStorageSync('code', options.query.code);
			}

			// #ifdef APP-PLUS
			// App平台检测升级，服务端代码是通过uniCloud的云函数实现的，详情可参考：https://ext.dcloud.net.cn/plugin?id=2226
			// #endif
			//获取设备顶部窗口的高度（不同设备窗口高度不一样，根据这个来设置自定义导航栏的高度）
			uni.getSystemInfo({
				success: res => {
					this.globalData.barHeight = res.statusBarHeight;
					this.globalData.screenWidth = res.screenWidth;
					this.globalData.screenHeight = res.screenHeight;
					this.globalData.viewHeight = res.windowHeight;
				}
			});

			//应用通知（消息推送）
			// uniPush1.getPushClientId()
			// #ifdef APP-PLUS
			// plus.push.getClientInfoAsync((info) => {
			//   let cid = info["clientid"];
			//   uni.setStorageSync('cid', cid)

			//   // this.cid = cid
			//   console.log(cid)
			// });
			// // #endif
			// that.getPush()
			/**
			 * 校验session_key是否失效
			 * 如果失效，则清空登录态，当需要登录的时候，从login.wxml重新登录
			 */
			// uni.checkSession({
			//   success() {
			//     // sessionKey有效没有过期
			//     console.log("checkSession success");
			//   },
			//   fail() {
			//     // sessionKey已经失效，过期
			//     console.log("checkSession fail");
			//     // 清空登录所有相关信息
			//     // clearLoginStatus();
			//   },
			// });
			
			// 客服
			// #ifdef APP-PLUS
			// 关闭启动画面，锁定竖屏
			// @ts-ignore
			plus.navigator.closeSplashscreen();
			// @ts-ignore
			plus.screen.lockOrientation("portrait-primary");
			// #endif
			// @ts-ignore
			if (
				// @ts-ignore
				uni.$UIKitStore &&
				// @ts-ignore
				uni.$UIKitStore?.connectStore?.connectState === "connected"
			) {
				return;
			}
			// @ts-ignore
			const imOptions = uni.getStorageSync('toke') || true;
			// 登录逻辑您根据实际业务逻辑自行实现，在您的登录页完成登录后，将您的业务服务器返回的 account、token 传入 app.vue 里的初始化登录 IM 的方法，待 IM 初始化、连接完成后，再重定向到您需要的界面。
			if (imOptions) {
				this.getKeyFun();
			} else {
				// 需要登录 im
				uni.navigateTo({
					url: '/pages/research/register/login'
				});
			}
		},
		onShow: function() {
			// #ifdef APP-PLUS
			setTimeout(function() {
				var args = plus.runtime.arguments;

				if (args) {
					console.log(args);
					let res = args.split('&');
					let pageType = res[1].split('=')[1];
					let type = res[2].split('=')[1];
					let id = res[3].split('=')[1];
					let shareId = res[4].split('=')[1];
					let teamId = res[5].split('=')[1];
					// 普通商品
					if (pageType == 1 && type == 1) {
						uni.navigateTo({
							url: '/pages/product/goods/goods?id=' + id + '&shareId=' + shareId
						});
					}
					//积分商品
					if (pageType == 1 && type == 5) {
						uni.navigateTo({
							url: '/pages/product/goods/IntegralGood?id=' + id + '&shareId=' + shareId
						});
					}
					//服务商品
					if (pageType == 1 && type == 4) {
						uni.navigateTo({
							url: '/pages/product/goods?id=' + id + '&shareId=' + shareId
						});
					}
					//秒杀商品
					if (pageType == 1 && type == 2) {
						uni.navigateTo({
							url: '/pages/product/goods?id=' + id + '&shareId=' + shareId
						});
					}
					//团购商品
					if (pageType == 1 && type == 3) {
						console.log('555555555');
						uni.navigateTo({
							url: '/pages/product/goods?id=' + id + '&shareId=' + shareId + '&teamId=' +
								teamId
						});
					}
					//文章
					if (pageType == 2) {
						console.log('6666666');
						uni.navigateTo({
							url: '/pages/research/recommend/details?id=' + id + '&shareId=' + shareId
						});
					}
					// 作品
					if (pageType == 3) {
						console.log('777777777777');
						uni.navigateTo({
							url: '/pages/research/business/article?id=' + id + '&shareId=' + shareId
						});
					}
					if (pageType == 4) {
						uni.navigateTo({
							url: '/pages/research/register/login'
						});
					}
				}
			}, 10);
			// #endif
			
			// #ifdef APP-PLUS
			// @ts-ignore
			const nimSdk = uni?.$UIKitNIM?.getNIM();
			nimSdk?.offlinePush?.updateAppBackground({
				isBackground: false,
			});
			// #endif
		},
		methods: {
			// 获取imappKey
			async getKeyFun() {
				const personal = uni.getStorageSync('personal')
				let res = await this.$http.post(getKey)
				if (res.data.appKey) {
					this.getCheckUserInfo(personal.mobile, res.data.appKey)
				}
			},
			// im用户检测
			async getCheckUserInfo(userId, appKeys) {
				let res = await this.$http.post(checkUserInfo, { userId: userId })
				this.initNim({
					account: res.data.accid,
					token: res.data.token,
					appKey: appKeys
				})
			},
			initNim(opts : {
				account : string; token : string; appKey : string;
			}) {
				// 保存登录信息
				// @ts-ignore
				uni.setStorage({
					key: opts.token,
					data: opts,
					success: function () {
						console.log("保存登录信息success");
					},
				});
				// @ts-ignore
				console.log(uni.$UIKitNIM)
				const nim = (uni.$UIKitNIM = new NimKitCore({
					initOptions: {
						appkey: opts.appKey, // 请填写你的appkey
						account: opts.account, // 请填写你的account
						token: opts.token, // 请填写你的token
						// account: opts.account, // 请填写你的account
						// token: opts.token, // 请填写你的token
						lbsUrls: isWxApp ? ["https://lbs.netease.im/lbs/wxwebconf.jsp"] : [
							"https://lbs.netease.im/lbs/webconf.jsp"
						],
						linkUrl: isWxApp ? "wlnimsc0.netease.im" : "weblink.netease.im",
						needReconnect: true,
						/**
						 * 使用固定设备ID，
						 */
						isFixedDeviceId: true,
						// "reconnectionAttempts": 5,
						debugLevel: "debug",
						// ...opts,
					},
					platform: "UniApp",
				}));
			
				// @ts-ignore
				const store = (uni.$UIKitStore = new RootStore(nim, {
					addFriendNeedVerify: false,
					teamBeInviteMode: "noVerify",
					teamJoinMode: "noVerify",
					teamUpdateExtMode: "manager",
					teamUpdateTeamMode: "manager",
					teamInviteMode: "manager",
					sendMsgBefore: async (options : any, type : IMMessage["type"]) => {
						const pushContent = getMsgContentTipByType({
							body: options.body,
							type,
						});
						const yxAitMsg = options.ext ?
							options.ext.yxAitMsg : {
								forcePushIDsList: "[]",
								needForcePush: false
							};
			
						// 如果是 at 消息，需要走离线强推
						// @ts-ignore
						const {
							forcePushIDsList,
							needForcePush
						} = yxAitMsg
								? // @ts-ignore
								store.msgStore._formatExtAitToPushInfo(yxAitMsg, options.body) : {
									forcePushIDsList: "[]",
									needForcePush: false
								};
			
						console.log("forcePushIDsList: ", forcePushIDsList);
			
						// 不同产商的推送消息体
						const {
							scene,
							to
						} = options;
						const pushPayload = JSON.stringify({
							// oppo
							oppoField: {
								click_action_type: 4, // 参考 oppo 官网
								click_action_activity: "", // 各端不一样 TODO
								action_parameters: {
									sessionId: scene,
									sessionType: to
								}, // 自定义
							},
			
							// vivo
							vivoField: {
								pushMode: 0, //推送模式 0：正式推送；1：测试推送，不填默认为0
							},
			
							// huawei
							hwField: {
								click_action: {
									type: 1,
									action: "", // 各端不一样 TODO
								},
								androidConfig: {
									category: "IM",
									data: JSON.stringify({
										sessionId: to,
										sessionType: scene
									}),
								},
							},
			
							// 通用
							sessionId: to,
							sessionType: scene,
						});
			
						const pushInfo : any = {
							needPush: true,
							needPushBadge: true,
							pushPayload: "{}",
							pushContent,
							needForcePush,
							forcePushIDsList,
							forcePushContent: pushContent,
						};
						return {
							...options,
							pushInfo
						};
					},
				}));
			
				// #ifdef APP-PLUS
				// 注册推送
				nim.getNIM().offlinePush.setOfflinePushConfig({
					plugin: nimPushPlugin,
					authConfig: {
						// xiaomi
						xmAppId: "",
						xmAppKey: "",
						xmCertificateName: "",
			
						// huawei
						hwAppId: "",
						hwCertificateName: "",
			
						// oppo
						oppoAppId: "",
						oppoAppKey: "",
						oppoAppSecret: "",
						oppoCertificateName: "",
			
						/** vivo
						 * 注意vivo的appid和appkey需要同时在此处，以及manifest.json(即插件参数配置)中配置
						 */
						vivoAppId: "",
						vivoAppKey: "",
						vivoCertificateName: "",
			
						// fcm
						fcmCertificateName: "",
			
						// meizu
						mzAppId: "",
						mzAppKey: "",
						mzCertificateName: "",
			
						// iOS
						apnsCertificateName: "",
					},
				});
			
				// #endif
				nim.connect();
				// nim.on('disconnect', function (obj) { console.log('已断开连接', obj) })
			
				// nim.on('willReconnect', function (q) {
			
				// 	console.log('收到了重连事件' , q)
				// })
			
				// customSwitchTab({
				// 	url: "/pages/Conversation/index",
				// });
			},
			//跳转
			jump(item, obj) {
				let that = this
				if (item.type == 0) {
					let activityType = obj.activity_type
					if (activityType == 1) {
						uni.navigateTo({
							url: "/pages/research/nearby/timeLimit"
						})
					}
					if (activityType == 2) {
						uni.navigateTo({
							url: "/pages/research/homepage/groupList"
						})
					}
				}
				//支付消息
				if (item.type == 1) {
					let goodsType = obj.goods_type
					if (goodsType == 0) {
						let id = obj.order_id
						uni.navigateTo({
							url: `/pages/order/orderList/orderDetails?id=${id}&status=pay`
						})
						//普通商品完成
					}
					if (goodsType == 1) {
						let id = obj.order_id
						uni.navigateTo({
							url: `/pages/order/orderList/serviceOrderDetail?id=${id}&status=pay`
						})
						//服务详情完成
					}
					if (goodsType == 2) {
						let id = obj.order_id
						if (obj.activity_type == 2) {
							uni.navigateTo({
								url: "/pages/order/gbOrder/gbOrderDetails?id=" + id +
									'&status=pay' + "&groupId=" + obj.goods[0].team_member_id
							})
						}
						//跳转秒杀详情地址还没写上去
						else if (obj.activity_type == 1) {
							uni.navigateTo({
								// url:"/pages/product/goods/seckillGoods?id="+obj.goods[0].goods_id
								url: `/pages/order/orderList/orderDetails?id=${id}&status=pay`
							})
						}
					}
					//积分商品
					if (goodsType == 3) {
						let id = obj.order_id
						uni.navigateTo({
							url: `/pages/order/orderList/orderDetails?id=${id}&status=pay`
						})
						//完成
					}
					// if (goodsType == 4) {
					//   uni.navigateTo({
					//     url: "/pages/user/wallet/transactionDetail"
					//   })
					// }
				}
				//物流消息
				if (item.type == 2) {
					let logisticsStatus = obj.logistics_status
					if (logisticsStatus == 0) {
						let id = obj.order_id
						uni.navigateTo({
							url: `/pages/order/orderList/orderDetails?id=${id}&status=pay`

						})
					}
					if (logisticsStatus == 1) {
						let id = obj.order_id
						uni.navigateTo({
							url: `/pages/order/orderList/orderDetails?id=${id}&status=pay`
						})
					}
				}
				//售后消息
				if (item.type == 3) {
					let id = obj.rights_order_id
					console.log(id)
					that.$http.get(`/rights/info/${id}`).then(res => {
						if (res && res.code == 200) {
							let shopid = res.data.shop_id
							let rightsType = res.data.rights_type
							let rightsRefundStatus = res.data.rights_operate_status
							uni.navigateTo({
								url: "/pages/order/orderList/orderblackDetails?id=" + id +
									"&shopid=" +
									shopid + "&type=" + rightsType + "&status=" +
									rightsRefundStatus
							})
						} else {
							uni.showToast({
								title: '无此订单',
								icon: 'none',
								duration: 2000
							});
						}
					})
					//先全部跳售后详情
				}
				// 互动消息
				if (item.type == 4) {
					let id = item.user_id
					let personalType = obj.type
					// if (personalType == 0 || personalType == 2) {
					//   let id = obj.model_id
					//   uni.navigateTo({
					//     url: "/pages/research/recommend/details?id=" + id
					//   })
					// } else if (personalType == 1) {
					//   let id = item.user_id
					//   uni.navigateTo({
					//     url: "/pages/research/community/homepage?user_id=" + id
					//   })
					// } else if (personalType == 3) {
					//   let id = obj.model_id
					//   uni.navigateTo({
					//     url: "/pages/research/setup/toExamine?id=" + id
					//   })
					// } else if (personalType == 4) {

					//   let id = obj.model_id
					//   uni.navigateTo({
					//     url: "/pages/research/setup/toBusiness?id=" + id
					//   })
					// }
					if (personalType == 4) {
						// let id = obj.model_id
						uni.navigateTo({
							url: "/pages/user/merchant/audit"
						})
					} else if (personalType == 5) {
						uni.navigateTo({
							url: "/pages/workbench/shop/audit"
						})
					}
				}
				// 系统消息
				if (item.type == 5) {
					if (obj.type == 0) {
						uni.navigateTo({
							url: `/pages/user/regional-agency/index`
						})
					}
				}
			},
			getPush() {
				// #ifdef APP-PLUS
				plus.push.setAutoNotification(true); //设置通知栏显示通知必须设置
				//从系统消息中心点击消息启动应用事件
				let that = this
				let platform = uni.getSystemInfoSync().platform;
				plus.push.addEventListener("click", (data) => {
					// JSON.parse(data.payload)
					// uni.setClipboardData({
					// 	data: data,
					// 	success: function(res) {
					// 		uni.showToast({
					// 			title: '复制成功',
					// 		});
					// 	}
					// });
					// uni.showModal({
					// 	title: '苹果离线提示11' + Object.prototype.toString.call(data) + 'type::'+data.type,
					// 	content: JSON.stringify(data),
					// 	success: function(res) {
					// 		if (res.confirm) {
					// 			console.log('用户点击确定');
					// 		} else if (res.cancel) {
					// 			console.log('用户点击取消');
					// 		}
					// 	}
					// });
					if (platform == 'ios' && data.type == 'click') { //苹果离线点击事件
						let obj = data.payload.payload.message_body
						let item = data.payload.payload
						that.jump(item, obj)
					}
					if (platform == 'ios') { //苹果在线点击事件
						let item = JSON.parse(data.payload)
						let obj = item.message_body
						that.jump(item, obj)
					}
					if (platform == 'android') { //安卓在线点击事件
						let item = data.payload
						let obj = item.message_body
						that.jump(item, obj)
					}
				}, false)
				//应用从推送服务器接收到推送消息事件
				plus.push.addEventListener("receive", (res) => {
					if (platform == 'android') { //安卓在线推送
						// item = res.payload
						var options = {
							cover: false,
							title: res.title
						};
						plus.push.createMessage(res.content, res.payload, options);
						// uni.showModal({
						// 	title: '安卓在线提示11' + Object.prototype.toString.call(res.payload),
						// 	content: JSON.stringify(res.payload),
						// 	success: function(r) {
						// 		if (r.confirm) {
						// 			console.log('用户点击确定');
						// 		} else if (r.cancel) {
						// 			console.log('用户点击取消');
						// 		}
						// 	}
						// });
					} else {
						//苹果在线推送事件
						if (res.aps == null || res.type == 'receive') {
							var options = {
								cover: false,
								title: res.title
							};
							plus.push.createMessage(res.content, JSON.stringify(res.payload), options);
						}
					}
				}, false)
				// #endif
			}
		},
		onHide: function() {
			// #ifdef APP-PLUS
			// @ts-ignore
			const nimSdk = uni?.$UIKitNIM?.getNIM();
			nimSdk?.offlinePush?.updateAppBackground({
				isBackground: true,
			});
			// #endif
		},
		globalData: {
			test: ''
		}
	};
</script>

<style lang="scss">
	//全局引入u-view ui框架样式
	@import 'uview-ui/index.scss';
	/* #ifndef APP-PLUS-NVUE */
	@import '@/common/style/common.scss';

	/* uni.css - 通用组件、模板样式库，可以当作一套ui库应用 */
	@import './common/style/uni.css';

	/* #endif */
	uni-radio .uni-radio-input .uni-radio-input-checked {
		background: #ff0000 !important;
	}

	.uni-modal {
		width: 635rpx !important;
		height: auto;
		background: #FFFFFF;
		border-radius: 19rpx 19rpx 19rpx 19rpx;
		background-color: yellow;
		max-width: 635rpx !important;

		// .uni-modal__hd {
		//    font-weight: 500;
		//    font-size: 33rpx;
		//    color: #333333;
		//    line-height: 33rpx;
		// }
		.uni-modal__bd {
			font-weight: 500;
			font-size: 33rpx;
			color: #333333;
			line-height: 33rpx;
			height: 196rpx;
			padding-top: 76rpx;
			padding-bottom: 87rpx;
			box-sizing: border-box;
		}

		.uni-modal__ft {
			width: 557rpx;
			height: 85rpx;
			margin-left: 38rpx;
			padding-bottom: 100rpx;
		}


		.uni-modal__btn {
			font-size: 32.69rpx;
			font-weight: 500;
		}

		.uni-modal__btn_default {
			width: 269rpx;
			height: 85rpx;
			background: #FFFFFF;
			border-radius: 19rpx 19rpx 19rpx 19rpx;
			border: 2rpx solid #FF211F;
			font-weight: 500;
			font-size: 29rpx;
			color: #FF211F !important;
			line-height: 34rpx;
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;

		}

		.uni-modal__btn_primary {
			width: 269rpx;
			height: 85rpx;
			background: #FF211F;
			border-radius: 19rpx 19rpx 19rpx 19rpx;
			font-weight: 500;
			font-size: 29rpx;
			color: #FFFFFF !important;
			line-height: 34rpx;
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			margin-left: 19rpx;
		}


	}

	.status-bar {
		height: 20px;
		/* 默认值，如果不需要动态设置可以直接写固定值 */
		width: 100%;
		position: relative;
	}
</style>